package org.fluidripple.socket.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.fluidripple.socket.inbound.ClientEventHandler;
import org.fluidripple.socket.operation.CKSUMCalculator;
import org.fluidripple.socket.operation.ChannelOperation;
import org.fluidripple.socket.session.Magnification;
import org.fluidripple.socket.session.Session;
import org.fluidripple.socket.session.SessionManager;
import org.fluidripple.socket.stickhalf.FixedLengthDecoderImpl;
import org.fluidripple.socket.wrapper.DataWrapper;
import org.springframework.stereotype.Component;

@Component
public class DeviceSetMagnificationProtocol extends Protocol{

    private Integer a;
    private Integer b;


    public DeviceSetMagnificationProtocol() {
    }

    public DeviceSetMagnificationProtocol(Integer a, Integer b) {
        this.a = a;
        this.b = b;
    }
    @Override
    public void writer(Channel channel) {
        Session session = SessionManager.getSession(channel);
        session.setProtocol(this);
        ChannelOperation.replaceChannelHandler(channel, ClientEventHandler.name, FixedLengthDecoderImpl.name,new FixedLengthDecoderImpl(7));
        byte[] bytes = ByteBufUtil.decodeHexDump("F0C105B0");
        ByteBuf buffer = Unpooled.buffer(7);
        buffer.writeBytes(bytes);
        buffer.writeByte(a);
        buffer.writeByte(b);

        ByteBuf checkBuf = Unpooled.buffer(4);
        checkBuf.writeBytes(buffer,2,2);
        checkBuf.writeByte(a);
        checkBuf.writeByte(b);
        int checksum = CKSUMCalculator.calculateChecksum(checkBuf.array());
        buffer.writeByte(checksum);
        channel.writeAndFlush(buffer);
    }

    @Override
    public void toDecode(DataWrapper dataWrapper) {
        Session session = dataWrapper.getSession();
        Magnification magnification = session.getMagnification();
        magnification.setA(a);
        magnification.setB(b);
    }
}
